package serveur;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import org.apache.log4j.Logger;

public class ThreadDialogue implements Runnable {

	private final static Logger logger = Logger.getLogger(ThreadDialogue.class);

	PrintWriter out;
	BufferedReader in;
	static Socket socket;
	String ip;
	int port = 0;

	public ThreadDialogue(Socket socket) {
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
			ip = socket.getInetAddress().getHostAddress();
			port = socket.getPort();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void run() {
		out.println("Connexion TCP etablie");
		String message = "";
		boolean continuer = true;
		while (continuer == true) {
			try {
				message = in.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(message);
			String text = "";
			if (getTypeRequete(message).equals("GET")) {
				if (verifierRequeteGet(message)) {
					String[] requete = message.split(" ");

					File fichier = new File(requete[1]);
					if (fichier.exists()) {
						try {
							text = _GET(message, out);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						text = text + "\n <CR> <LF>";
					} else {
						text = "HTTP/1.1 404 Not Found \n <CR> <LF>";
						logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);
					}
				} else {
					text = "HTTP/1.1 400 Bad Request \n <CR> <LF>";
					logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);
				}
			} else if (message.equalsIgnoreCase("FIN")) {
				continuer = false;
			} else {
				logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);
				text = "HTTP/1.1 400 Bad Request \n <CR> <LF>";

			}
			out.println(text);
		}
		logger.info("Fermeture de la connexion avec le client : " + ip + ":" + port);
		System.out.println("Fermeture de la connexion du client");
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		out.close();
	}

	private String _GET(String message, PrintWriter out) throws IOException {
		String text = "";
		String[] requete = message.split(" ");
		File fichier = new File(requete[1]);
		String nomFichier = requete[1];
		double taille = fichier.length();
		if (fichier.exists()) {
			BufferedReader br = null;
			String ligne = "";
			text = "HTTP/1.1 200 OK \n";
			logger.info("Reception du message: " + text + "ip : " + ip + ":" + port);
			text = text + "Content-length: " + taille + "\n";
			br = new BufferedReader(new FileReader(nomFichier));
			while ((ligne = br.readLine()) != null) {
				text = text + ligne + "\n";
			}
		}
		return text;
	}

	private static String getTypeRequete(String message) {
		return message.split(" ")[0];
	}

	private static boolean verifierRequeteGet(String message) {
		boolean verification = false;
		String[] requete = message.split(" ");
		if (requete.length == 5) {
			if (requete[0].equals("GET") && (requete[2].equals("HTTP/1.1") || requete[2].equals("HTTP/1.0")) && requete[3].equals("<CR>") && requete[4].equals("<LF>")) {
				verification = true;
			}
		}
		return verification;
	}
}
